<?php
//by willson 105328468@qq.com 2014/10/13
//member module interface

class cart extends core {
	public $goods_mod;
	public $order_mod;
	public $commission_mod;
	public $coupon_mod;

	public function __construct() {
		parent::__construct();
		$this->goods_mod = m("goods");
		$this->order_mod = m("order");
		$this->commission_mod = m("commission");
		$this->coupon_mod = m("coupon");
	}

	//购物车数量
	public function cart_total($isFilter=false, $isReturn=false) {
		$goods_id = (isset($_POST['goods_id']) && trim($_POST['goods_id'])) ? trim($_POST['goods_id']) : 0;
		$spec = (isset($_POST['spec']) && trim($_POST['spec'])) ? trim($_POST['spec']) : '';
		//先判断该规格是否还存在
		if ($goods_id) {
			$sql = "SELECT count(*) FROM jf_goods_spec WHERE goods_id='{$goods_id}' AND spec='{$spec}'";
			$count = $this->db->get_var($sql);
			if (!$count) error("该商品规格已下架");
		}
		$quantity = 0;
		$total_price = 0;
		//$sql = "SELECT IFNULL(SUM(quantity),0) FROM jf_cart WHERE 1";
		$sql = "SELECT price, quantity FROM jf_cart WHERE goods_id>0";
		if ($this->member_id>0) {
			$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$sql .= " AND session_id='".session_id()."'";
		}
		if ($isFilter) {
			if ($goods_id>0) $sql .= " AND goods_id='{$goods_id}'";
			if ($spec) $sql .= " AND spec='{$spec}'";
		}
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$quantity += $g->quantity;
				$total_price += $g->price * $g->quantity;
			}
		}
		if ($isReturn) {
			return array('quantity'=>$quantity, 'total_price'=>$total_price);
		} else {
			success(array('quantity'=>$quantity, 'total_price'=>$total_price));
		}
	}

	//加入到购物车
	public function add_cart() {
		$goods = (isset($_POST['goods']) && trim($_POST['goods'])) ? stripslashes($_POST['goods']) : '';
		//邀请我的渠道商的店铺id
		//$reseller_id = (isset($_POST['reseller']) && trim($_POST['reseller'])) ? trim($_POST['reseller']) : 0;
		$reseller_id = (isset($_SESSION['reseller_id']) && intval($_SESSION['reseller_id'])) ? intval($_SESSION['reseller_id']) : 0;
		//操作是根据quantity值, 传1:当前操作是购物车修改商品总数量, 0:进行累加(数字)/累减(-数字)
		$edit = (isset($_POST['edit']) && trim($_POST['edit'])) ? trim($_POST['edit']) : 0;

		if ($goods) {
			$goods = json_decode($goods);
			if (is_array($goods) && count($goods)) {
				foreach ($goods as $k=>$g) {
					//获取价格
					$sql = "SELECT price FROM jf_goods WHERE id='{$g->goods_id}'";
					$price = $this->db->get_var($sql);
					$sql = "SELECT id, quantity FROM jf_cart WHERE goods_id='{$g->goods_id}' AND spec='{$g->spec}'";
					if ($this->member_id>0) {
						$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
					} else {
						$sql .= " AND session_id='".session_id()."'";
					}
					$rs = $this->db->get_row($sql);
					if ($rs) {
						if (!$edit) {
							if (intval($g->quantity)<0 && $rs->quantity-intval($g->quantity)<=0) {
								$sql = "DELETE FROM jf_cart WHERE id='{$rs->id}'";
							} else {
								$sql = "UPDATE jf_cart SET quantity=quantity+{$g->quantity} WHERE id='{$rs->id}'";
							}
						} else {
							if (intval($g->quantity)<=0) {
								$sql = "DELETE FROM jf_cart WHERE id='{$rs->id}'";
							} else {
								$sql = "UPDATE jf_cart SET quantity='{$g->quantity}' WHERE id='{$rs->id}'";
							}
						}
					} else {
						$shop_id = $this->db->get_var("SELECT shop_id FROM jf_goods WHERE id='{$g->goods_id}'");
						$sql = "INSERT INTO jf_cart (member_id, session_id, goods_id, quantity, spec, ip, add_time, shop_id, reseller_id, price)
								VALUES ('{$this->member_id}', '".session_id()."', '{$g->goods_id}', '{$g->quantity}', '{$g->spec}', '{$this->ip}', '".time()."', '{$shop_id}', '{$reseller_id}', '{$price}')";
					}
					$this->db->query($sql);
				}
			}
		}
		$this->cart_total();
	}

	//从购物车删除
	public function del_cart() {
		$cart_id = (isset($_POST['cart_id']) && trim($_POST['cart_id'])) ? trim($_POST['cart_id']) : 0;
		if ($cart_id<=0) error('数据错误');
		$sql = "DELETE FROM jf_cart WHERE id='{$cart_id}'";
		if ($this->member_id>0) {
			$sql .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$sql .= " AND session_id='".session_id()."'";
		}
		$this->db->query($sql);
		$this->cart_total();
	}

	//购物车首页
	//支持分单，不需要分单，按照默认即可（shop_id=0）
	public function index() {
		//print_r($_SESSION);
		$filter = '';
		if ($this->member_id>0) {
			$filter .= " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
		} else {
			$filter .= " AND session_id='".session_id()."'";
		}
		$sql = "SELECT COUNT(DISTINCT(shop_id)) FROM jf_cart WHERE 1 {$filter}";
		$count = $this->db->get_var($sql);
		if ($count>1) {
			$sql = "SELECT shop_id FROM jf_cart WHERE 1 {$filter}";
		} else {
			$sql = "SELECT DISTINCT(shop_id) FROM jf_cart WHERE 1 {$filter}";
		}
		//$sql .= " ORDER BY id ASC";
		//exit($sql);
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k=>$s) {
				$sql = "SELECT name, avatar FROM jf_shop WHERE id='{$s->shop_id}'";
				$row = $this->db->get_row($sql);
				if ($row) {
					$rs[$k]->shop_name = $row->name;
					$rs[$k]->shop_avatar = $row->avatar;
				}
				$sql = "SELECT c.id, c.goods_id, c.spec, c.quantity, c.reseller_id, 
					g.name, g.default_pic, g.price, g.promote_price, g.stocks 
					FROM jf_cart c LEFT JOIN jf_goods g ON c.goods_id=g.id 
					WHERE c.shop_id='{$s->shop_id}' AND g.status='1' {$filter}";
				$goods = $this->db->get_results($sql);
				if ($goods) {
					foreach ($goods as $gk=>$g) {
						//获取价格
						$sql = "SELECT * FROM jf_goods_spec WHERE goods_id='{$g->goods_id}' AND spec='{$g->spec}'";
						$row = $this->db->get_row($sql);
						if ($row) {
							$goods[$gk]->price = $row->promote_price>0 ? $row->promote_price : $row->price;
							$goods[$gk]->stocks = $row->stocks;
						}
					}
				}
				$rs[$k]->goods = $goods;
			}
		}
		$rs = add_domain_deep($rs, array("pic", "default_pic", "shop_avatar"));
		success($rs);
	}

	//结算接口
	public function jiesuan() {
		//print_r($_SESSION);
		//分单
		if ($this->member_id<=0) error('请登录', -100);
		//使用积分抵扣
		$integral_cash = (isset($_POST['integral_cash']) && trim($_POST['integral_cash'])) ? trim($_POST['integral_cash']) : 0;
		//积分商城订单
		$integral_order = (isset($_POST['integral_order']) && trim($_POST['integral_order'])) ? trim($_POST['integral_order']) : 0;
		$shops = $this->_split_shops();
		$goods_ids = $this->_get_goods_ids($shops);
		$shops = add_domain_deep($shops, array("default_pic"));
		$total_price = $this->_get_total_price($shops);
		
		//获取默认地址
		//require_once(APP_PATH . "/address.php");
		$address_model = m("address");
		$address = $address_model->default_address();
		
		//获取用户的佣金、余额、积分
		$money = 0; //佣金和余额之和
		$integral = 0; //积分
		$sql = "SELECT money, commission, integral FROM jf_member WHERE id='{$this->member_id}'";
		$member = $this->db->get_row($sql);
		if ($member) {
			$money = $member->money + $member->commission;
			$integral = $member->integral;
		}
		$coupons = $this->coupon_mod->coupons($this->member_id, $total_price, $goods_ids);
		
		//积分抵扣
		$integral_pay = null;
		if ($integral_cash) {
			if ($this->order_mod->order_integral_check($this->member_id, $total_price)) {
				$integral_pay = $this->order_mod->check_pay_with_integral($total_price);
			}
		}
		
		//计算总运费, 积分商城订单免运费
		$shipping_fee = 0;
		if (is_array($shops) && !$integral_order) {
			foreach ($shops as $s) {
				$shipping_fee += $s->shipping_fee;
			}
		}
		
		success(array("address" => $address, "money"=>$money, "total_price"=>$total_price, "integral_order"=>$integral_order, "shipping_fee"=>$shipping_fee, "integral"=>$integral, "integral_pay"=>$integral_pay, "coupons"=>$coupons, "shops" => $shops));
	}

	//下单接口
	public function order($is_show=true) {
		//支付方式
		$pay_method = (isset($_POST['pay_method']) && trim($_POST['pay_method'])) ? trim($_POST['pay_method']) : 'wxpay';
		$coupon_sn = (isset($_POST['coupon_sn']) && trim($_POST['coupon_sn'])) ? trim($_POST['coupon_sn']) : '';
		//积分抵扣
		$integral_cash = (isset($_POST['integral_cash']) && trim($_POST['integral_cash'])) ? intval($_POST['integral_cash']) : 0;
		//积分商城订单
		$integral_order = (isset($_POST['integral_order']) && trim($_POST['integral_order'])) ? intval($_POST['integral_order']) : 1;
		//收货地址
		$province = (isset($_POST['province']) && trim($_POST['province'])) ? trim($_POST['province']) : '';
		$city = (isset($_POST['city']) && trim($_POST['city'])) ? trim($_POST['city']) : '';
		$district = (isset($_POST['district']) && trim($_POST['district'])) ? trim($_POST['district']) : '';
		$address = (isset($_POST['address']) && trim($_POST['address'])) ? trim($_POST['address']) : '';
		$zipcode = (isset($_POST['zipcode']) && trim($_POST['zipcode'])) ? trim($_POST['zipcode']) : '';
		$mobile = (isset($_POST['mobile']) && trim($_POST['mobile'])) ? trim($_POST['mobile']) : '';
		$contactman = (isset($_POST['contactman']) && trim($_POST['contactman'])) ? trim($_POST['contactman']) : '';
		$idcard = (isset($_POST['idcard']) && trim($_POST['idcard'])) ? trim($_POST['idcard']) : '';
		$invoice_type = (isset($_POST['invoice_type']) && trim($_POST['invoice_type'])) ? trim($_POST['invoice_type']) : '';
		$invoice_name = (isset($_POST['invoice_name']) && trim($_POST['invoice_name'])) ? trim($_POST['invoice_name']) : '';
		$invoice_content = (isset($_POST['invoice_content']) && trim($_POST['invoice_content'])) ? trim($_POST['invoice_content']) : '';
		
		//分单
		$shops = $this->_split_shops();
		$total_price = $this->_get_total_price($shops);
		///print_r($shops);
		//exit;

		//先生成订单号，在用余额支付的时候可以用上
		//余额支付
		if ($pay_method=="yue") {
			if ($this->order_mod->is_yue_and_commission_enough($total_price)) {
				$status = 1;
				$pay_time = time();
			} else {
				error("您的佣金和余额不足以支付");
			}
		} else {
			$status = 0;
			$pay_time = 0;
		}
		
		//积分商城订单
		if ($integral_order) {
			$sql = "SELECT integral FROM jf_member WHERE id='{$this->member_id}'";
			$integral = $this->db->get_var($sql);
			if ($integral < $total_price) error('您的积分不足以支付');
		}
		
		//优惠券金额
		$coupon_money = 0;
		if ($coupon_sn && $total_price) {
			$goods_ids = $this->_get_goods_ids($shops);
			$coupons = $this->coupon_mod->coupons($this->member_id, $total_price, $goods_ids);
			$coupon_money = $this->coupon_mod->valid($coupon_sn, $coupons); 
			$total_price = $total_price - $coupon_money;
			if ($total_price < 0) $total_price = 0;
		}
		
		//积分抵扣
		$integral_pay = null;
		$integral_money = 0; //使用积分抵现
		$integral_value = 0; //使用了多少积分
		if ($integral_cash && $total_price>0) {
			$integral_pay = $this->order_mod->check_pay_with_integral($total_price);
			$integral_money = $integral_pay->money;
			$integral_value = $integral_pay->integral;
			$total_price = $total_price - $integral_money;
		}
		
		if ($integral_order || $total_price == 0) {
			$status = 1;
			$pay_time = time();
		}

		//总订单SN，用来提交到支付宝，回调时提取出相关订单设置状态
		$parent_order_sn = generate_order_sn();
		//生成单号，写入数据库
		$inegral_order_sn = '';
		if ($shops) {
			foreach ($shops as $k=>$shop) {
				$order_sn = generate_order_sn();
				$inegral_order_sn = $order_sn;
				$is_resell = 0;
				if (isset($_SESSION['reseller_id'])) {
					$reseller_id = intval($_SESSION['reseller_id']);
				}
				//写入订单表
				$sql = "INSERT INTO jf_order(member_id, province, city, district, address, zipcode, name, idcard, mobile, 
					total_price, shipping_price, discount_price, coupon_sn, status, add_time, pay_time, ip, 
					order_sn, shop_id, parent_order_sn, pay_method, 
					invoice_type, invoice_name, invoice_content, used_coupon, used_integral, integral, integral_order)
					VALUES('{$this->member_id}', '{$province}', '{$city}', '{$district}', '{$address}', '{$zipcode}', '{$contactman}', '{$idcard}', '{$mobile}', 
					'{$shop->total_price}', '{$shop->shipping_fee}', '0', '{$coupon_sn}', '{$status}', '".time()."', '{$pay_time}', '{$this->ip}', 
					'{$order_sn}', '{$shop->shop_id}', '{$parent_order_sn}', '{$pay_method}', 
					'{$invoice_type}', '{$invoice_name}', '{$invoice_content}', '{$coupon_money}', '{$integral_money}', '{$integral_value}', '{$integral_order}')";
				$this->db->query($sql);
				$order_id = $this->db->insert_id;
				//用余额支付，扣减余额和财富
				if ($pay_method == 'yue') {
					$this->order_mod->pay_with_yue_and_commission($total_price, $order_id);
				}
				//写入订单商品表
				foreach ($shop->goods as $j=>$g) {
					$goods_price = $this->get_goods_price($g->price, $g->promote_price);
					$sql = "INSERT INTO jf_order_goods(shop_id, member_id, order_id, goods_id, goods_name, goods_pic,
							spec, price, quantity)
							VALUES('{$shop->shop_id}', '{$this->member_id}', '{$order_id}', '{$g->id}', '".addslashes($g->name)."', '{$g->default_pic}',
							'{$g->spec}', '{$goods_price}', '{$g->quantity}')";
					$this->db->query($sql);
				}
				//有邀请人的，需要写入返利情况
				if ($_SESSION['member']->parent_id) {
					$this->commission_mod->add($_SESSION['member']->parent_id, $order_id, 1);
				}
			}
			//使用优惠券
			$this->coupon_mod->using($coupon_sn, $this->member_id);
		}
		
		//减去会员抵扣的积分
		if ($integral_cash && $integral_pay) {
			$sql = "UPDATE jf_member SET integral=integral-{$integral_pay->integral} WHERE id='{$this->member_id}'";
			$this->db->query($sql);
			$sql = "INSERT INTO jf_member_integral_history (member_id, memo, integral, add_time,order_sn) 
				VALUES ('{$this->member_id}', '订单积分抵扣', '-{$integral_pay->integral}', '".time()."','{$inegral_order_sn}')";
			$this->db->query($sql);
		}
		
		//积分商城订单，减去会员对应积分
		if ($integral_order) {
			$sql = "UPDATE jf_member SET integral=integral-{$total_price} WHERE id='{$this->member_id}'";
			$this->db->query($sql);
			$sql = "INSERT INTO jf_member_integral_history (member_id, memo, integral, add_time,order_sn) 
				VALUES ('{$this->member_id}', '积分商城商品兑换', '-{$total_price}', '".time()."','{$inegral_order_sn}')";
			$this->db->query($sql);
		}
		
		//要写入session，by willson 2015/9/2
		$pay_method_name = '';
		switch ($pay_method) {
			case 'alipay':$pay_method_name = '支付宝支付';break;
			case 'wxpay':case 'wxpay_h5':$pay_method_name = '微信支付';break;
			case 'yue':$pay_method_name = '余额支付';break;
			case 'integral':$pay_method_name = '积分支付';break;
		}
		$_SESSION['order_sn'] = $parent_order_sn;
		$_SESSION['order_price'] = $total_price;
		$_SESSION['total_price'] = $total_price;
		$_SESSION['pay_method_name'] = $pay_method_name;

		//20160316 by ajsong 需要同时删除购物车表里面对应的记录
		$goods = (isset($_POST['goods']) && trim($_POST['goods'])) ? stripslashes($_POST['goods']) : '';
		if ($goods && !$integral_order) {
			$goods = json_decode($goods);
			if (is_array($goods) && count($goods)) {
				$where = '';
				if ($this->member_id>0) {
					$where = " AND (member_id='{$this->member_id}' OR session_id='".session_id()."')";
				} else {
					$where = " AND session_id='".session_id()."'";
				}
				foreach ($goods as $k=>$g) {
					$sql = "DELETE FROM jf_cart WHERE goods_id='{$g->goods_id}' AND spec='{$g->spec}' {$where}";
					$this->db->query($sql);
				}
			}
		}

		if ($is_show) {
			//如果有多个订单，order_id为最后一个
			success(array("order_id"=>$order_id, "order_sn"=>$parent_order_sn, "total_price"=>$integral_order?0:$total_price));
		}
	}


	//下单接口,微信端用,因为涉及到需要即时跳转去支付
	public function order_pay() {
		//判断是否从结算那里提交过来，如果是，表示是新订单，清空订单SESSION
		$goods_json = (isset($_POST['goods']) && trim($_POST['goods'])) ? stripslashes($_POST['goods']) : '';
		if ($goods_json) {
			$_SESSION['order_sn'] = '';
			$_SESSION['order_price'] = '';
			$_SESSION['pay_method_name'] = '';
			$_SESSION['total_price'] = '';
		}
		$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
		$order_price = (isset($_SESSION['order_price']) && trim($_SESSION['order_price'])) ? floatval($_SESSION['order_price']) : 0;
		$order_body = '商富商城订单';
		$pay_method_name = (isset($_SESSION['pay_method_name']) && trim($_SESSION['pay_method_name'])) ? trim($_SESSION['pay_method_name']) : '';
		$total_price = (isset($_SESSION['total_price']) && floatval($_SESSION['total_price'])) ? floatval($_SESSION['total_price']) : 0;
		if ($order_sn=='' || $order_price<=0) {
			$pay_method_name = (isset($_POST['pay_method_name']) && trim($_POST['pay_method_name'])) ? trim($_POST['pay_method_name']) : '';
			$total_price = (isset($_POST['total_price']) && trim($_POST['total_price'])) ? trim($_POST['total_price']) : '';
			$this->order(false);
			$order_sn = (isset($_SESSION['order_sn']) && trim($_SESSION['order_sn'])) ? trim($_SESSION['order_sn']) : '';
			$order_price = (isset($_SESSION['order_price']) && trim($_SESSION['order_price'])) ? floatval($_SESSION['order_price']) : 0;
		}
		if ($order_sn=='' || $order_price<=0) {
			error('订单信息错误！');
		}
		
		//注释这两行，因为$pay_method_name从微信回调时是没有任何内容的;
		//by willson 2015-09-02
		//$_SESSION['pay_method_name'] = $pay_method_name;
		//$_SESSION['total_price'] = $total_price;
		/**
		 * JS_API支付demo
		 * ====================================================
		 * 在微信浏览器里面打开H5网页中执行JS调起支付。接口输入输出数据格式为JSON。
		 * 成功调起支付需要三个步骤：
		 * 步骤1：网页授权获取用户openid
		 * 步骤2：使用统一支付接口，获取prepay_id
		 * 步骤3：使用jsapi调起支付
		*/
		include_once(FRAMEWORK_PATH . "/class/wxapi/WxPayPubHelper/WxPayPubHelper.php");

		//使用jsapi接口
		$jsApi = new JsApi_pub();

		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		$openid = '';
		if (!isset($_GET['code'])){
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(urlencode("http://".$_SERVER['SERVER_NAME']."/wap.php?app=cart&act=order_pay"));
			//echo $url;
			//exit;
			header("Location: {$url}");
			exit;
		}else{
			//获取code码，以获取openid
			$code = $_GET['code'];
			//echo $code;
			//exit;
			$jsApi->setCode($code);
			$openid = $jsApi->getOpenid();
		}
		
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();

		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$unifiedOrder->setParameter("openid", "$openid");
		$unifiedOrder->setParameter("body", "$order_body");//商品描述
		if($order_sn==''){
			//自定义订单号，此处仅作举例
			$timeStamp = time();
			$order_sn = WxPayConf_pub::APPID."$timeStamp";
		}
		$unifiedOrder->setParameter("out_trade_no", "$order_sn");//商户订单号
		$unifiedOrder->setParameter("total_fee", $order_price*100);//总金额,单位:分
		$unifiedOrder->setParameter("notify_url", "http://".$_SERVER['SERVER_NAME']."/wx_notify_url.php");//通知地址
		$unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

		$prepay_id = $unifiedOrder->getPrepayId();
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);

		$jsApiParameters = $jsApi->getParameters();
		//exit($jsApiParameters);
		//$_SESSION['order_sn'] = '';
		//$_SESSION['order_price'] = '';
		//$_SESSION['pay_method_name'] = '';
		//$_SESSION['total_price'] = '';
		
		success($jsApiParameters, '成功', 0, array("pay_method_name"=>$pay_method_name, "total_price"=>$total_price, "order_sn"=>$order_sn));
	}
	
	//扫码支付
	public function native() {
		$order_sn = (isset($_GET['order_sn']) && trim($_GET['order_sn'])) ? trim($_GET['order_sn']) : '';
		$url = (isset($_GET['url']) && trim($_GET['url'])) ? trim($_GET['url']) : '';
		success(array('order_sn'=>$order_sn, 'url'=>$url));
	}

	//检查订单状态
	public function check_order_status() {
		$order_sn = isset($_GET['order_sn']) ? trim($_GET['order_sn']) : '';
		$sql = "SELECT count(*) FROM jf_order WHERE (order_sn='{$order_sn}' OR parent_order_sn='{$order_sn}') 
			AND (pay_method='wxpay' OR pay_method='wxpay_h5') AND status>0";
		$count = $this->db->get_var($sql);
		success($count);
	}

	//下单成功后，需要调用此接口，用来更新库存和销量，并发送消息推送给卖家。
	public function order_complete() {
		$parent_order_sn = (isset($_GET['order_sn']) && trim($_GET['order_sn'])) ? trim($_GET['order_sn']) : '';
		if ($parent_order_sn) {
			//减少库存，增加销量，发送通知
			$sql = "SELECT o.* FROM jf_order o 
				WHERE o.status='1' AND parent_order_sn='{$parent_order_sn}' AND handle_after_paid='0'";
			$orders = $this->db->get_results($sql);
			//更新订单处理后的标识，以后不再发送推送和更新销量。
			$sql = "UPDATE jf_order SET handle_after_paid='1' WHERE parent_order_sn='{$parent_order_sn}'";
			$this->db->query($sql);
			//20150728 by ajsong 兼容在订单列表支付成功的调用，那个地方是单独一张单的，不是购物车那种的合单
			if (!$orders) {
				$sql = "SELECT o.* FROM jf_order o 
					WHERE o.status='1' AND order_sn='{$parent_order_sn}' AND handle_after_paid='0'";
				$orders = $this->db->get_results($sql);
				//更新订单处理后的标识，以后不再发送推送和更新销量。
				$sql = "UPDATE jf_order SET handle_after_paid='1' WHERE order_sn='{$parent_order_sn}'";
				$this->db->query($sql);
			}
			//print_r($orders);
			if ($orders) {
				$order_ids = array();
				foreach ($orders as $k=>$o) {
					$order_ids[] = $o->id;
				}
				$order_ids = implode(',', $order_ids);
				//echo $order_ids;
				if ($order_ids) {
					$goods_ids = array();
					$sql = "SELECT og.goods_id, og.quantity, g.stocks
						FROM jf_order_goods og INNER JOIN jf_goods g ON g.id=og.goods_id
						WHERE og.order_id IN ({$order_ids})";
					$goods = $this->db->get_results($sql);
					if ($goods) {
						foreach ($goods as $k=>$g) {
							$status = 1;
							$stocks = $g->stocks - $g->quantity;
							if ($stocks <= 0)  {
								$stocks = 0;
								$status = -1; //下架
							}
							$sql = "UPDATE jf_goods SET stocks='{$stocks}', status='{$status}', sales=sales+1 WHERE id='{$g->goods_id}'";
							//echo $sql."<br>";
							$this->db->query($sql);
							//同步所有下家的商品库存
							//$sql = "UPDATE jf_goods SET stocks='{$stocks}', status='{$status}' WHERE parent_id='{$g->goods_id}'";
							//echo $sql."<br>";
							//$this->db->query($sql);
						}
					}
				}
				//发送消息推送
				foreach ($orders as $k=>$o) {
					//发送消息给用户
					if ($o->member_id) {
						//$this->send_notify("您的订单{$o->order_sn}已经支付成功，请耐心等待卖家发货。", $o->member_id);
						//send_sms($o->mobile, $o->order_sn, 72076);
						$this->send_notify_sms("您的订单{$o->order_sn}已经支付成功，请耐心等待卖家发货。", $o->member_id, true, array($o->order_sn), 128220);
					}
				}
			}
			$_SESSION['order_sn'] = '';
			$_SESSION['order_price'] = '';
			$_SESSION['pay_method_name'] = '';
			$_SESSION['total_price'] = '';
		}
		success("ok");
	}

	//根据提交的产品数据来分单，返回分单后的店铺
	private function _split_shops() {
		$goods = $shops = $shop_ids = array();
		$goods_ids = "";
		$goods = (isset($_POST['goods']) && trim($_POST['goods'])) ? stripslashes($_POST['goods']) : '';
		//是否积分商城订单
		$integral_order = (isset($_POST['integral_order']) && trim($_POST['integral_order'])) ? trim($_POST['integral_order']) : 0;
		if (!$goods) error('请选择商品');
		$origin_goods = json_decode($goods);
		if (!$origin_goods) error('请选择商品');
		//$origin_goods = $origin_goods->goods;
		//print_r($origin_goods);
		//为了避免购买同一个产品的不同规格时，只显示一个产品的问题
		//直接查询, 每个产品查询一次，可能会导致效率问题
		$goods = array();
		foreach ($origin_goods as $k => $g) {
			$where = '';
			if (isset($g->spec)) {
				$where = " AND gs.spec='{$g->spec}'";
			} else if ($integral_order) {
				$sql = "SELECT spec FROM jf_goods_spec WHERE goods_id='{$g->goods_id}' ORDER BY id ASC";
				$row = $this->db->get_row($sql);
				$where = " AND gs.spec='{$row->spec}'";
			}
			$sql = "SELECT g.id, g.name, g.default_pic, g.shop_id, g.price, g.integral, g.promote_price, g.shipping_fee, 
				gs.spec, 0 as quantity, gs.price as spec_price, gs.promote_price as spec_promote_price 
				FROM jf_goods g INNER JOIN jf_goods_spec gs ON g.id=gs.goods_id
				WHERE g.id='{$g->goods_id}' {$where}";
			//echo $sql;
			$row = $this->db->get_row($sql);
			if ($row) {
				$row->price = $row->spec_promote_price>0 ? $row->spec_promote_price : $row->spec_price;
				$row->quantity = $g->quantity;
				$goods[] = $row;
				$shop_ids[] = $row->shop_id;
			}
		}
		//print_r($goods);
		if (count($goods)) {
			//print_r($goods);
			//exit;
			$shop_ids = implode(',', $shop_ids);
			//if ($shop_ids) {
				$single_shop = false; //兼容单店铺的项目,清空店铺表里的所有记录或者goods表的shop_id设为0即自动转为单店铺
				$sql = "SELECT id as shop_id, name as shop_name, avatar as shop_avatar, 0 as total_price, 0 as shipping_fee, '' as goods 
					FROM jf_shop
					WHERE id IN ({$shop_ids})";
				$shops = $this->db->get_results($sql);
				if (!$shops) {
					$shop_obj = new stdClass();
					$shop_obj->shop_id = 0;
					$shop_obj->total_price = 0;
					$shop_obj->shipping_fee = 0;
					$shop_obj->goods = '';
					$shops[0] = $shop_obj;
					$single_shop = true;
				}
				//计算每个店铺的商品价格
				foreach ($goods as $k=>$g) {
					foreach ($shops as $j=>$shop) {
						//兼容单店铺的项目
						if ($single_shop) {
							if ($integral_order) {
								$integral = $g->integral;
								if (isset($origin_goods[0]->spec)) { //兼容积分订单有可能需要规格
									$sql = "SELECT price FROM jf_goods_spec WHERE goods_id='{$g->id}' AND spec='{$origin_goods[0]->spec}' ORDER BY id ASC";
									$r = $this->db->get_row($sql);
									if ($r) $integral = intval($r->price);
								}
								$g->integral = $integral;
								$shops[$j]->total_price += $integral * $g->quantity;
							} else {
								$goods_price = $this->get_goods_price($g->price, $g->promote_price);
								$shops[$j]->total_price += $goods_price * $g->quantity;
							}
							$shops[$j]->goods[] = $g;
						} else {
							//同一个店铺内的
							if ($g->shop_id==$shop->shop_id) {
								if ($integral_order) {
									//获取商品的积分
									$integral = $g->integral;
									if (isset($origin_goods[0]->spec)) { //兼容积分订单有可能需要规格
										$sql = "SELECT price FROM jf_goods_spec WHERE goods_id='{$g->id}' AND spec='{$origin_goods[0]->spec}' ORDER BY id ASC";
										$r = $this->db->get_row($sql);
										if ($r) $integral = intval($r->price);
									}
									$g->integral = $integral;
									$shops[$j]->total_price += $integral * $g->quantity;
								} else {
									//获取商品的价格
									$goods_price = $this->get_goods_price($g->price, $g->promote_price);
									$shops[$j]->total_price += $goods_price * $g->quantity;
								}
								$shops[$j]->goods[] = $g;
								break;
							}
						}
					}
				}
				//计算每个店铺的运费
				foreach ($shops as $k=>$shop) {
					$shops[$k]->shipping_fee = $this->caculate_shipping_fee($shop->goods);
					if ($integral_order) $shops[$k]->shipping_fee = 0; //积分商城订单免运费
					if ($shops[$k]->shipping_fee) {
						$shops[$k]->total_price += $shops[$k]->shipping_fee;
					}
				}
			//}
		}
		//$shops = add_domain_deep($shops, array("default_pic"));
		return $shops;
	}

	//获取订单总价
	private function _get_total_price($shops) {
		$total_price = 0;
		if ($shops) {
			foreach ($shops as $k=>$shop) {
				$total_price += $shop->total_price;
			}
		}
		return $total_price;
	}

	//获取商品价格
	//需要考虑是否批发会员，是否到了起批量
	public function get_goods_price($price, $promote_price) {
		if ($promote_price>0 && $promote_price<$price) {
			return $promote_price;
		} else {
			return $price;
		}
	}

	//判断该会员是否该店铺的批发会员
	public function is_reseller($shop_id) {
		$sql = "SELECT count(*) FROM jf_shop_reseller WHERE shop_id='{$shop_id}' AND member_id='{$this->member_id}'";
		return intval($this->db->get_var($sql));
	}

	//计算运费，只计算商品里运费最高的
	public function caculate_shipping_fee($goods) {
		$shipping_fee = 0;
		if ($goods) {
			foreach ($goods as $k=>$g) {
				if ($g->shipping_fee>$shipping_fee) {
					$shipping_fee = $g->shipping_fee;
				}
			}
		}
		return $shipping_fee;
	}

	//查看某个订单的商品是否还可以购买
	//该函数用在会员中心未支付的订单点击支付时，需要判断商品库存是否足够、商品是否下架等
	public function check_order_goods() {
		$order_id = (isset($_GET['order_id']) && intval($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		if ($order_id && $this->member_id) {
			$sql = "SELECT og.shop_id, og.goods_id, og.goods_name, g.stocks, g.status, g.id, og.quantity
				FROM jf_order_goods og INNER JOIN jf_order o ON og.order_id=o.id
				LEFT JOIN jf_goods g ON og.goods_id=g.id
				WHERE o.id='{$order_id}' AND o.member_id='{$this->member_id}'";
			$goods = $this->db->get_results($sql);
			if ($goods) {
				foreach ($goods as $k => $g) {
					$goods_name = mb_substr($g->goods_name, 0, 6);
					if (!intval($g->id)) error("商品（{$goods_name}）已经失效");
					if (intval($g->stocks) <= 0) error("商品（{$goods_name}）已经下架");
					if (intval($g->status) == 0) error("商品（{$goods_name}）已经下架");
					if ($g->quantity > $g->stocks) error("商品（{$goods_name}）库存不足");
				}
				success("ok");
			} else {
				error("商品已经失效");
			}
		} else {
			error("数据错误或没有登录");
		}
	}

	//根据shops数组来获取goods_id的数组
	private function _get_goods_ids($shops) {
		$ids = array();
		if ($shops) {
			foreach ($shops as $key => $shop) {
				if ($shop->goods) {
					foreach ($shop->goods as $j => $goods) {
						$ids[] = $goods->id;
					}
				}
			}
			$ids = array_unique($ids);
		}
		return $ids;
	}
}
